/*
 * utf8gbk_table.c
 *
 *  Created on: 2016年2月29日
 *      Author: yami
 */

/**
 * @file	utf8gbk_table.c
 * @author	yami
 * @date	2016年2月29日
 * @brief
 * 
 */

#define UTFOFFSET 0x4e00



const static unsigned short unicodes_tables[] = {
#include "ucodegbk.txt"
};


/**
 *
 * @param data	文本数据
 * @return		高8位为数据长度， 低16位是gbk编码
 */
unsigned int utf8togbk(void*data)
{
	unsigned int 	unicode;
	unsigned char 	*text;
	text	=	data;
	unsigned int result;
	int		len;
	int		i;
	/*
	error
	*dst++	=	0x83;
	*dst++	=	0x9B;
	 */
	result		=	0;
	unicode		=	0;
	if(text[0]<0x7f){
		//result	=	1<<(0x18);		//0x18
		if(!text[0])
			return 0;
		len		=	1;
		result	|=	text[0];
		return result;
	}
	else if(text[0]<0xE0){
		//result	=	2<<(0x18);		//0x18
		len		=	2;
		unicode	|=	((text[0]&0x1f));

	}
	else if(text[0]<0xf0){
		len		=	3;
		unicode	|=	((text[0]&0xf));
//		unicode	<<=	6;
//		unicode |=	((text[1]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[2]&0x3f));
	}
	else if(text[0]<0xf8){
		//result	=	4<<(0x18);		//0x18
		len		=	4;
		unicode	|=	((text[0]&0x7));
//		unicode	<<=	6;
//		unicode |=	((text[1]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[2]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[3]&0x3f));
	}
	else if(text[0]<0xfc){
		//result	=	5<<(0x18);		//0x18
		len		=	5;
		unicode	|=	((text[0]&0x3));
//		unicode	<<=	6;
//		unicode |=	((text[1]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[2]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[3]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[4]&0x3f));
	}
	else if(text[0]<0xfe){
		//result	=	6<<(0x18);		//0x18
		len		=	6;
		unicode	|=	((text[0]&0x1));
//		unicode	<<=	6;
//		unicode |=	((text[1]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[2]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[3]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[4]&0x3f));
//		unicode <<=	6;
//		unicode |=	((text[5]&0x3f));
	}
	else{
		return (0xf<<0x18)|(0x9b83);
	}

	for(i=1;i<len;i++){
		unicode	<<=	6;
		if(!text[i]){
			return (i<<0x18)|(0x9b83);
		}
		unicode |=	((text[i]&0x3f));
	}

	unicode	-=	UTFOFFSET;
	if(unicode>(sizeof(unicodes_tables)>>1)){
		return (0xf<<0x18)|(0x9b83);
	}
	return (len<<0x18)|(unicodes_tables[unicode]);
}

